package cn.lxkroom.crm.test;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.lxkroom.crm.dao.UserDao;
import cn.lxkroom.crm.domain.User;
import cn.lxkroom.crm.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DBtest {
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	@Resource(name="userDao")
	private UserDao userDao;

	@Test
	//单独测试Hibernate的使用
	public void fun1(){
		Configuration configure = new Configuration().configure();
		SessionFactory factory = configure.buildSessionFactory();
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		User u=new User();
		u.setUser_code("lucy");
		session.save(u);
		tx.commit();
		session.close();
		factory.close();
	}
	@Test
	//测试spring管理sessionFactory
	public void fun2(){
		System.out.println(sessionFactory);
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		User u=new User();
		u.setUser_code("lili");
		session.save(u);
		tx.commit();
		session.close();
		sessionFactory.close();
	}
	@Test
	//测试spring管理sessionFactory,Hibernate配置文件配置到spring中
	public void fun3(){
		//System.out.println(sessionFactory);
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		User u=new User();
		u.setUser_code("美美");
		session.save(u);
		tx.commit();
		session.close();	
		sessionFactory.close();
	}
	
	@Resource(name="userService")
	private UserService userService;
	@Test
	//测试spring管理sessionFactory,Hibernate配置文件配置到spring中,
	//加入c3p0连接池,hibernate模板,Dao,测试dao
	public void fun4(){
		System.out.println(userDao);
		User u=new User();
		u.setUser_code("lilei");
		//此时,如果没有配置事务,会报异常
		userService.save(u);
	}
}
